
package com.wwy.monitor.service.impl;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.wwy.monitor.model.vo.MailMessageVO;
import com.wwy.monitor.service.McFactory;
import com.wwy.monitor.service.NoticeService;
import com.autonavi.acis.system.mail.MailTemplateDao;
import com.autonavi.acis.system.mail.model.MailTemplate;
import com.autonavi.acis.system.mail.render.NoticeRender;
import com.autonavi.acis.utils.RenderManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Author: ç³å éï¼ççï¼ Time: 2017/9/19
 */
@Service
public class NoticeServiceImpl implements NoticeService {
    private static final Logger LOGGER = LoggerFactory.getLogger(NoticeServiceImpl.class);
    @Autowired
    private MailTemplateDao mailTemplateDao;

    public void setMailTemplateDao(MailTemplateDao mailTemplateDao) {
        this.mailTemplateDao = mailTemplateDao;
    }

    @Override
    public boolean sendNotifyEmail(String templateName, Map<String, Object> parameters, List<String> emails) {
        return _sendMail(templateName, parameters, emails);
    }

    private boolean _sendMail(String templateName, Map<String, Object> parameters, List<String> emails) {
        MailTemplate template;
        try {
            template = mailTemplateDao.findByName(templateName);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return false;
        }
        String title = null;
        NoticeRender render = RenderManager.getRender(template.getTitleRender());
        if (render == null) {
            throw new IllegalArgumentException("Title render not found");
        }
        try {
            title = render.render(template.getTitle(), parameters);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        String content = null;
        render = RenderManager.getRender(template.getContentRender());
        if (render == null) {
            throw new IllegalArgumentException("Content render not found");
        }
        try {
            content = render.render(template.getContent(), parameters);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        try {
            MailMessageVO mailMessageVO = new MailMessageVO();
            mailMessageVO.setToMailList(emails);
            mailMessageVO.setMailTitle(title);
            mailMessageVO.setMailText(content);
            mailMessageVO.setHtmlText(render.isHtml());
            boolean success = McFactory.getMailMcService().sendMsg("system", mailMessageVO);
            LOGGER.info("Send mail [{}] to {}", title, emails);
            return success;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return false;
    }
}